#!/bin/bash

# EMS-CPP-V1 构建和启动脚本
# Build and Start Script for EMS-CPP-V1

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目信息
PROJECT_NAME="EMS-CPP-V1"
BUILD_DIR="build"
BIN_DIR="$BUILD_DIR/bin"
EXECUTABLE="ems-cpp-v1"
CONFIG_DIR="./config"
SKIP_WEB="false"  # 通过 --skip-web 或环境变量 SKIP_WEB=1 启用

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_header() {
    echo -e "${BLUE}=== $1 ===${NC}"
}

# 检查依赖
check_dependencies() {
    log_header "检查依赖"
    
    # 检查CMake
    if ! command -v cmake &> /dev/null; then
        log_error "CMake 未安装，请先安装 CMake"
        exit 1
    fi
    log_info "CMake: $(cmake --version | head -n1)"
    
    # 检查编译器
    if ! command -v g++ &> /dev/null && ! command -v clang++ &> /dev/null; then
        log_error "C++ 编译器未找到，请安装 GCC 或 Clang"
        exit 1
    fi
    
    if command -v g++ &> /dev/null; then
        log_info "编译器: $(g++ --version | head -n1)"
    else
        log_info "编译器: $(clang++ --version | head -n1)"
    fi
    
    # 检查依赖库
    if ! pkg-config --exists libmodbus; then
        log_error "libmodbus 未安装，请使用以下命令安装:"
        echo "  Ubuntu/Debian: sudo apt-get install libmodbus-dev"
        echo "  CentOS/RHEL:   sudo yum install libmodbus-devel"
        echo "  macOS:         brew install libmodbus"
        exit 1
    fi
    log_info "libmodbus: $(pkg-config --modversion libmodbus)"
    
    if ! pkg-config --exists libmosquitto; then
        log_error "libmosquitto 未安装，请使用以下命令安装:"
        echo "  Ubuntu/Debian: sudo apt-get install libmosquitto-dev"
        echo "  CentOS/RHEL:   sudo yum install mosquitto-devel"
        echo "  macOS:         brew install mosquitto"
        exit 1
    fi
    log_info "libmosquitto: $(pkg-config --modversion libmosquitto)"
}

# 清理构建目录
clean_build() {
    log_header "清理构建目录"
    if [ -d "$BUILD_DIR" ]; then
        rm -rf "$BUILD_DIR"
        log_info "已清理构建目录"
    else
        log_info "构建目录不存在，跳过清理"
    fi
}

# 配置项目
configure_project() {
    log_header "配置项目"
    mkdir -p "$BUILD_DIR"
    cd "$BUILD_DIR"
    
    cmake .. \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
    
    if [ $? -eq 0 ]; then
        log_info "项目配置成功"
    else
        log_error "项目配置失败"
        exit 1
    fi
    cd ..
}

# 构建Web前端
build_web() {
    log_header "构建Web前端"
    # 允许通过选项跳过前端构建
    if [ "${SKIP_WEB}" = "true" ] || [ "${SKIP_WEB}" = "1" ]; then
        log_warn "已启用 --skip-web，跳过前端构建"
        return 0
    fi
    
    if [ -f "./scripts/build-web.sh" ]; then
        log_info "构建Vue.js前端..."
        ./scripts/build-web.sh --skip-lint
        log_info "Web前端构建完成"
    else
        log_warn "未找到Web构建脚本，跳过前端构建"
    fi
}

# 编译项目
build_project() {
    log_header "编译项目"
    cd "$BUILD_DIR"
    
    # 检测CPU核心数
    if command -v nproc &> /dev/null; then
        CORES=$(nproc)
    elif command -v sysctl &> /dev/null; then
        CORES=$(sysctl -n hw.ncpu)
    else
        CORES=4
    fi
    
    log_info "使用 $CORES 个并行进程编译"
    make -j$CORES
    
    if [ $? -eq 0 ]; then
        log_info "C++编译成功"
    else
        log_error "C++编译失败"
        exit 1
    fi
    cd ..
}

# 检查配置文件
check_config() {
    log_header "检查配置文件"
    
    if [ ! -d "$CONFIG_DIR" ]; then
        log_error "配置目录不存在: $CONFIG_DIR"
        exit 1
    fi
    
    required_files=("devices.json" "mqtt.conf" "system.json")
    for file in "${required_files[@]}"; do
        if [ ! -f "$CONFIG_DIR/$file" ]; then
            if [ "$file" = "devices.json" ] && [ -f "$CONFIG_DIR/devices.template.json" ]; then
                cp "$CONFIG_DIR/devices.template.json" "$CONFIG_DIR/devices.json"
                log_warning "未找到 devices.json，已从模板复制，请按需修改后重试"
            elif [ "$file" = "mqtt.conf" ] && [ -f "$CONFIG_DIR/mqtt.template.conf" ]; then
                cp "$CONFIG_DIR/mqtt.template.conf" "$CONFIG_DIR/mqtt.conf"
                log_warning "未找到 mqtt.conf，已从模板复制，请按需修改后重试"
            else
                log_error "缺少配置文件: $CONFIG_DIR/$file"
                exit 1
            fi
        fi
        log_info "配置文件检查通过: $file"
    done
}

# 启动程序
start_program() {
    log_header "启动程序"
    
    if [ ! -f "$BIN_DIR/$EXECUTABLE" ]; then
        log_error "可执行文件不存在: $BIN_DIR/$EXECUTABLE"
        exit 1
    fi
    
    log_info "启动 $PROJECT_NAME..."
    log_info "配置目录: $CONFIG_DIR"
    log_info "使用 Ctrl+C 停止程序"
    echo
    
    "$BIN_DIR/$EXECUTABLE" --config "$CONFIG_DIR"
}

# 显示帮助信息
show_help() {
    echo "EMS-CPP-V1 构建和启动脚本"
    echo
    echo "用法: $0 [选项]"
    echo
    echo "选项:"
    echo "  build    编译项目(包含Web前端)"
    echo "  run      仅运行程序 (需要先编译)"
    echo "  start    编译并运行程序 (默认)"
    echo "  web      仅构建Web前端"
    echo "  clean    清理构建目录"
    echo "  deps     检查依赖"
    echo "  help     显示此帮助信息"
    echo
    echo "可选参数:"
    echo "  --skip-web   跳过Web前端构建(适用于 build/start)"
    echo
    echo "环境变量:"
    echo "  SKIP_WEB=1|true  跳过Web前端构建（等效 --skip-web）"
    echo
    echo "示例:"
    echo "  $0 --skip-web         # 编译并运行(跳过Web)"
    echo "  $0 build --skip-web   # 仅编译后端(跳过Web)"
    echo "  $0 build              # 仅编译(包含Web)"
    echo "  $0 web       # 仅构建Web前端"
    echo "  $0 run       # 仅运行"
    echo "  $0 clean     # 清理构建"
}

# 主函数
main() {
    log_header "轻量级能源管理系统 - $PROJECT_NAME"
    # 解析 --skip-web 与环境变量
    for arg in "$@"; do
        if [ "$arg" = "--skip-web" ]; then
            SKIP_WEB="true"
        fi
    done
    if [ "${SKIP_WEB}" != "true" ] && [ -n "${SKIP_WEB}" ] && [ "${SKIP_WEB}" -ne 0 ] 2>/dev/null; then
        SKIP_WEB="true"
    fi

    # 确定主命令（若首参是 --skip-web，则取第二参，默认 start）
    local CMD="start"
    if [ "${1:-}" = "--skip-web" ]; then
        CMD="${2:-start}"
    else
        CMD="${1:-start}"
    fi

    case "$CMD" in
        "build")
            check_dependencies
            clean_build
            configure_project
            build_web
            build_project
            log_info "编译完成！使用 '$0 run' 启动程序"
            ;;
        "run")
            check_config
            start_program
            ;;
        "start")
            check_dependencies
            clean_build
            configure_project
            build_web
            build_project
            check_config
            start_program
            ;;
        "web")
            build_web
            log_info "Web前端构建完成"
            ;;
        "clean")
            clean_build
            log_info "清理完成"
            ;;
        "deps")
            check_dependencies
            log_info "依赖检查完成"
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            log_error "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
}

# 信号处理
trap 'echo -e "\n${YELLOW}[WARN]${NC} 程序被中断"; exit 130' INT TERM

# 执行主函数
main "$@"
